{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
    .good-name, .good-price {
        line-height: 34px;
    }
    .wholesale-inut-len{
        width:60px !important;
    }
</style>
{/block}
{block name="main"}
<div class="layui-collapse ns-tips">
    <div class="layui-colla-item">
        <h2 class="layui-colla-title">操作提示</h2>
        <ul class="layui-colla-content layui-show">
            <li>管理员可以在此页添加批发商品</li>
        </ul>
    </div>
</div>

<div class="layui-form ns-form">



    <div class="layui-form-item goods_list">
        <label class="layui-form-label">商品：</label>
        <div class="layui-input-block" id="sku_list"></div>
    </div>
    <button class="layui-btn ns-bg-color ns-form-row" onclick="addGoods()">选择商品</button>
    <div class="ns-form-row">
        <button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>
        <button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
    </div>
    <input type="hidden" name="goods_ids" value=""/>
</div>


<!-- 操作 -->
<script type="text/html" id="sku_html">
    <table class="layui-table">
        <colgroup>
            <col width="300">
            <col width="200">
            <col width="100">
            <col width="300">
            <col width="100">
        </colgroup>
        <thead>
        <tr>
            <th>商品信息</th>
            <th>商品原价</th>
            <th>库存</th>
            <th>阶梯价格</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>

        {{#  if(d.length === 0){ }}
        <tr><td colspan="5">无数据</td></tr>
        {{# }else{ }}

        {{#  layui.each(d, function(index, item){ }}
        <tr>
            <td>
                <div class="ns-table-title">
                    <div class="ns-title-pic">
                        <img layer-src src="{{ ns.img(item.sku_image) }}"/>
                    </div>
                    <div class="ns-title-content">
                        <a href="javascript:;" class="ns-multi-line-hiding ns-text-color" title="{{ item.sku_name }}">{{ item.sku_name }}</a>
                    </div>
                </div>
            </td>
            <td>
                ￥{{ item.price }}
            </td>
            <td>
                {{ item.stock }}
            </td>

            <td>
                <div class="ns-table-btn">
                    <table class="layui-table sku-block"  sku_id = "{{ item.sku_id }}"  sku_price = "{{ item.price }}" goods_id = "{{ item.goods_id }}">
						<colgroup>
						    <col width="10%">
						    <col width="83%">
						    <col width="7%">
						</colgroup>
                        <tbody>
                            <tr>
                                <td style="min-width:40px;">数量</td>
                                <td><input type="number" name='num[]' class="layui-input wholesale-inut-len num" value="" lay-verify="required|number|int|gtzero" autocomplete="off" /></td>
                                <td rowspan="3"><a href="javascript:void(0);"  class="layui-icon layui-icon-add-circle" style='font-size:20px'onclick="addPricemodel(this);"></a></td>
                            </tr>
                            <tr>
                                <td style="min-width:40px;">价格</td>
                                <td><input type="number" name='price[]' class="layui-input wholesale-inut-len price" value="" lay-verify="required|number|int|price|gtzero" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td style="min-width:40px;">操作</td>
                                <td><a href="javascript:;" class="layui-btn" onclick="deletePricemodel(this)">删除</a></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </td>
            <td>
                <a class="layui-btn" onclick="delRow(this,{{item.sku_id}})">删除</a>
            </td>
        </tr>
        {{#  }); }}

        {{#  } }}
        </tbody>
    </table>
</script>
{/block}
{block name="script"}
<script>
    renderSku([]);

    layui.use(['form','laytpl'], function () {
        var form = layui.form, repeat_flag = false;

        form.render();

        /**
         * 表单验证
         */
        form.verify({
            gtzero: function (value, item) {
                if (value <= 0) {
                    return "批发的价格或数量不能小于或等于0";
                }
            },
            price : function (value, item) {
                var sku_price = $(item).parents('.sku-block').attr('sku_price');
                if (parseFloat(value) > parseFloat(sku_price)) {
                    return "阶梯价格不能大于商品原价";

                }
            },
        });

        /**
         * 表单提交
         */
        form.on('submit(save)', function (data) {
            var field = data.field;
            if (field.goods_ids == '') {
                layer.msg('请选择参与活动的商品！', {icon: 5, anim: 6});
                return;
            }
            var item_list = $(".sku-block");

            var sku_list = [];
            item_list.each(function(){
                var goods_id = $(this).attr('goods_id');

                var item_price_list = $(this).find('tr');
                var sku_id = $(this).attr('sku_id');

                if(item_price_list.length == 0){
                    layer.msg('规格阶梯价格不能为空！', {icon: 5, anim: 6});
                    return;
                }
                var first_item = $(this).find('tr:eq(0)');
                var second_item = $(this).find('tr:eq(1)');
                var num_item_list = first_item.find('.num');
                if(num_item_list.length == 0){
                    layer.msg('规格阶梯价格不能为空！', {icon: 5, anim: 6});
                    return;
                }
                var temp_list = [];
                num_item_list.each(function(index,element){
                    var index = $(element).parent().index();
                    var num = $(element).val();
                    var price = second_item.find('td:eq('+index+')').find('.price').val();
                    temp_list.push({num:num,price:price});
                });
                sku_list.push({sku_id:sku_id,sku_data:temp_list,goods_id:goods_id});
            });

            var price_json = JSON.stringify(sku_list);
            // if (repeat_flag) return;
            // repeat_flag = true;
            data.field.price_json = price_json;
            $.ajax({
                type: 'POST',
                dataType: 'JSON',
                url: ns.url("wholesale://shop/wholesale/add"),
                data: data.field,
                async: false,
                success: function (res) {
                    repeat_flag = false;

                    if (res.code == 0) {
                        layer.confirm('添加成功', {
                            title: '操作提示',
                            btn: ['返回列表', '继续添加'],
                            yes: function () {
                                location.href = ns.url("wholesale://shop/wholesale/lists");
                            },
                            btn2: function () {
                                location.href = ns.url("wholesale://shop/wholesale/add");
                            }
                        });
                    } else {
                        layer.msg(res.message);
                    }
                }
            })
        });
    });

    /**
     * 渲染sku规格信息
     */
    function renderSku(data) {
        layui.use(['laytpl'], function () {
            var laytpl = layui.laytpl;
            laytpl($("#sku_html").html()).render(data, function (html) {
                $("#sku_list").html(html);
            });
        })

    }

    /**
     * 添加商品
     */
    var  goodsId = [], selectedGoodsId = [], sku_list = [];
    function addGoods(){
        goodsSelect(function(res) {
            if (!res.length) return false;

            for(var i=0;i<res.length;i++) {

                goodsId['goods_'+ res[i].goods_id] = {};
                goodsId['goods_'+ res[i].goods_id].sku_id = {};
                goodsId['goods_'+ res[i].goods_id].spu_id = res[i].goods_id;

                for (var k = 0; k < res[i].selected_sku_list.length; k++) {
                    var item = res[i].selected_sku_list[k];

                    goodsId['goods_'+ res[i].goods_id].sku_id['sku_'+item.sku_id]={};
                    goodsId['goods_'+ res[i].goods_id].sku_id['sku_'+item.sku_id].sku = item.sku_id;
                    sku_list.push(item);
                }
            }

            renderSku(sku_list);
            var spuId = [];
            Object.values(goodsId).forEach(function (item,index) {
                spuId.push(item.spu_id);
            });
            selectedGoodsId = spuId.toString();
            $("input[name='goods_ids']").val(selectedGoodsId);
        }, selectedGoodsId);
    }


    function back() {
        location.href = ns.url("wholesale://shop/wholesale/lists");
    }


    /**
     * 添加阶梯价
     */
    function addPricemodel(obj) {
        var index = $(obj).parent().index();
        if($(obj).parent().parent().find('td').length == 5){
            layer.msg('阶梯价格设置不能超过3个！', {icon: 5, anim: 6});
            return false;
        }

        $(obj).parent().before('<td><input type="number" class="layui-input wholesale-inut-len num" lay-verify="required|gtzero" autocomplete="off" name="num[]" /></td>');
        var index = $(obj).parent().index();
        $(obj).parent().parent().next().append('<td><input type="number" class="layui-input wholesale-inut-len price" lay-verify="required|gtzero|price" autocomplete="off" name="price[]"/></td>');
        $(obj).parent().parent().next().next().append('<td><a href="javascript:;" class="layui-btn" onclick="deletePricemodel(this)">删除</a></td>');
    }

    /**
     * 删除阶梯价
     * @param e
     */
    function deletePricemodel(e) {
        var index = $(e).parent().index();
        if($(e).parent().parent().find('td').length == 2){
            layer.msg('阶梯价格至少要存在一个！', {icon: 5, anim: 6});
            return false;
        }
        $(e).parent().parent().parent().find('tr').each(function(){
            $(this).find('td:eq('+index+')').remove();
        });

    }

    function delRow(obj,id) {
        for (var i = 0; i < sku_list.length; i++){
            if (sku_list[i].sku_id == parseInt(id)){
                sku_list.splice(i,1);
            }
        }
        Object.values(goodsId).forEach(function (item,index) {
            delete item.sku_id['sku_'+id];
            if (!Object.keys(item.sku_id).length){
                delete goodsId['goods_'+item.spu_id];
            }
        });

        var spuId = [];
        Object.values(goodsId).forEach(function (item,index) {
            spuId.push(item.spu_id);
        });
        selectedGoodsId = spuId.toString();
        $("input[name='goods_ids']").val(selectedGoodsId);
        $(obj).parents("tr").remove();
    }
</script>
{/block}